package vn.orderonline.core.mail;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class SendMail implements ISendMail {
	
	private String mailFrom;
	private VelocityEngine velocityEngine;
	private JavaMailSender mailSender;
	
	public void setMailFrom(String mailFrom) {
		this.mailFrom = mailFrom;
	}
	
	public Boolean send(final String receiverEmail, final String url, final String templateName, final String title,
			final Map<String, Object> model) {
		try {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
					message.setFrom(new InternetAddress("ducthienx91@gmail.com"));
					message.setTo(new InternetAddress(receiverEmail));
					message.setSubject(title);
					String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8",
							model);
					message.setText(text, true);
				}
			};
			this.mailSender.send(preparator);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public void mailToOrder(final String receiver, final String orderCode) {
		try {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
					message.setFrom(new InternetAddress("zuchihashishui@gmail.com"));
					message.setTo(receiver);
					message.setSubject("Chúc mừng bạn đả đăt hàng thành công");
					Map<String, Object> model = new HashMap<>();
					model.put("mail", receiver);
					model.put("orderCode", orderCode);
					String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail.html", model);
					message.setText(text, true);
				}
			};
			this.mailSender.send(preparator);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}
}
